<script setup lang="ts">
import { getList } from '@/api/llm/api'
import { useRenderIcon } from '@/components/ReIcon/src/hooks'
import useDateRangeParams from '@/hooks/useDateRangeParams'
import { usePagination } from '@/hooks/usePagination'
import { useTableHeight } from '@/hooks/useTableHeight'
import useDictStore from '@/store/modules/dict'
import { ModalShowType } from '@/types/common'
import { formatDate, omitEmptyValue } from '@/utils/common'
import Refresh from '@iconify-icons/ep/refresh'
import Search from '@iconify-icons/ep/search'
import { FormInstance } from 'element-plus'
import { reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import apiDetailModal from './api-detail-modal.vue'

const { model_api_approve_status, model_type } = useDictStore().getDicts(
  'model_api_approve_status',
  'model_type'
)
const router = useRouter()
const searchParams = reactive({
  modelName: undefined,
  modelType: undefined,
  approveStatus: undefined,
})
const formRef = ref<FormInstance>()
const searchDateRange = ref<[Date, Date]>([null, null])
const { dateRangeParams } = useDateRangeParams(searchDateRange, 'YYYY-MM-DD HH:mm:ss', (s, e) => ({
  'params[beginApplySubmitTime]': s,
  'params[endApplySubmitTime]': e,
}))
const { pagination, paginationParams, changePageNumber, changePageSize } = usePagination(onSearch)
const columns: TableColumnList = [
  {
    type: 'selection',
    width: 55,
    align: 'left',
  },
  {
    label: '接口名称',
    prop: 'apiName',
    minWidth: 100,
  },
  {
    label: '接口地址',
    prop: 'apiUrl',
    minWidth: 150,
  },
  {
    label: '接口密钥',
    prop: 'apiKey',
    minWidth: 150,
  },
  {
    label: '模型名称',
    prop: 'modelName',
    minWidth: 100,
  },
  {
    label: '模型类别',
    prop: 'modelType',
    minWidth: 150,
    formatter: ({ modelType }) => model_type.getLabel(modelType),
  },
  {
    label: '消耗tokens',
    prop: 'tokens',
    minWidth: 150,
  },
  {
    label: '开始使用期限',
    prop: 'useTimeBegin',
    minWidth: 180,
    formatter: ({ useTimeBegin }) => formatDate(useTimeBegin) || '/',
  },
  {
    label: '结束使用期限',
    prop: 'useTimeEnd',
    minWidth: 180,
    formatter: ({ useTimeEnd }) => formatDate(useTimeEnd) || '/',
  },
  {
    label: '审批状态',
    prop: 'approveStatus',
    minWidth: 100,
    formatter({ approveStatus }) {
      return model_api_approve_status.getLabel(approveStatus)
    },
  },
  {
    label: '调用次数',
    prop: 'callNum',
    minWidth: 100,
  },
  {
    label: '操作',
    fixed: 'right',
    width: 180,
    slot: 'operation',
  },
]
const dataList = ref([])
const loading = ref(false)
const { tableHeight, tableRef } = useTableHeight()

/** 查询列表 */
async function onSearch() {
  loading.value = true
  const { rows, total } = await getList(
    omitEmptyValue({
      ...dateRangeParams.value,
      ...paginationParams.value,
      modelName: searchParams.modelName,
      modelType: searchParams.modelType,
      approveStatus: searchParams.approveStatus,
    })
  ).finally(() => {
    loading.value = false
  })

  dataList.value = rows
  pagination.total = total
}

/** 重置新增的表单  */
async function resetForm() {
  searchDateRange.value = [null, null]
  formRef.value.resetFields()
  onSearch()
}

const modalShow = ref(ModalShowType.Hide)
const props = reactive({
  apiName: undefined,
  apiUrl: undefined,
  apiKey: undefined,
  modelName: undefined,
  modelType: undefined,
  tokens: undefined,
  useTimeBegin: undefined,
  useTimeEnd: undefined,
  modelApiId: undefined as string | undefined,
})

onSearch()
</script>

<template>
  <div class="main table-view-layout">
    <div class="bg-white p-4 flex justify-between">
      <el-button type="primary" class="w-24 h-12" @click="router.push('/llm/api/apply')"
        >申请接口</el-button
      >
      <el-form
        ref="formRef"
        :inline="true"
        :model="searchParams"
        class="bg-el-bg w-[99/100] pl-8 pt-4"
      >
        <el-form-item prop="modelName">
          <el-input
            v-model="searchParams.modelName"
            placeholder="请输入模型名称"
            clearable
            style="width: 240px"
            @keyup.enter="onSearch"
          />
        </el-form-item>
        <el-form-item prop="modelType">
          <el-select
            v-model="searchParams.modelType"
            placeholder="模型类别"
            clearable
            class="!w-[180px]"
          >
            <el-option
              v-for="item in model_type"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item prop="approveStatus">
          <el-select
            v-model="searchParams.approveStatus"
            placeholder="审批状态"
            clearable
            class="!w-[180px]"
          >
            <el-option
              v-for="item in model_api_approve_status"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            :icon="useRenderIcon(Search)"
            :loading="loading"
            @click="onSearch"
          >
            搜索
          </el-button>
          <el-button :icon="useRenderIcon(Refresh)" @click="resetForm"> 重置 </el-button>
        </el-form-item>
      </el-form>
    </div>
    <PureTableBar>
      <template #table>
        <pure-table
          ref="tableRef"
          border
          align-whole="center"
          showOverflowTooltip
          table-layout="auto"
          :max-height="tableHeight"
          :loading="loading"
          :data="dataList"
          :columns="columns"
          :pagination="pagination"
          :header-cell-style="{
            background: 'var(--el-table-row-hover-bg-color)',
            color: 'var(--el-text-color-primary)',
          }"
          @page-size-change="changePageSize"
          @page-current-change="changePageNumber"
        >
          <template #operation="{ row }">
            <el-button
              link
              class="reset-margin"
              type="primary"
              @click="
                () => {
                  modalShow = ModalShowType.View
                  props.apiName = row.apiName
                  props.apiUrl = row.apiUrl
                  props.apiKey = row.apiKey
                  props.modelName = row.modelName
                  props.modelType = model_type.getLabel(row.modelType)
                  props.tokens = row.tokens
                  props.useTimeBegin = formatDate(row.useTimeBegin)
                  props.useTimeEnd = formatDate(row.useTimeEnd)
                  props.modelApiId = String(row.modelApiId)
                }
              "
            >
              查看
            </el-button>
          </template>
        </pure-table>
      </template>
    </PureTableBar>
    <apiDetailModal
      v-model:modalShow="modalShow"
      :apiName="props.apiName"
      :apiUrl="props.apiUrl"
      :apiKey="props.apiKey"
      :modelName="props.modelName"
      :modelType="props.modelType"
      :tokens="props.tokens"
      :useTimeBegin="props.useTimeBegin"
      :useTimeEnd="props.useTimeEnd"
      :on-search="onSearch"
      :modelApiId="props.modelApiId"
      @update:apiKey="(key) => { props.apiKey = key }"
    />
  </div>
</template>

<style scoped lang="scss">
:deep(.el-dropdown-menu__item i) {
  margin: 0;
}
</style>
